iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 10

完成 1 / 3 鐵人賽,調整刷題步調繼續前進

  • 分享至 

  • xImage
  •  

轉眼過了 10 天,堅持了 1/3 的鐵人賽
好幾度想放棄,還有許多事情要忙(專題、複習、研究文件、架網站等)
即便刷比較簡單的題目,也需要花一小時以上刷題、TDD、上傳、寫文章等
多希望自己體質是一天只要睡 2-3 小時 (離題遠了


Coderwars 題目已經刷到有點膩
即便如此,也要刷起來
目標是挑戰在 5 分鐘左右完成影片
這次 6 分鐘 3 題


題目(Summing a number's digits)

Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example:
  sumDigits 10    # Returns 1
  sumDigits 99    # Returns 18
  sumDigits -32   # Returns 5
Let's assume that all numbers in the input will be integer values.
def sumDigits(number)
end

Test.assert_equals(sumDigits(10), 1)
Test.assert_equals(sumDigits(99), 18)
Test.assert_equals(sumDigits(-32), 5)

題目(Sum of two lowest positive integers)

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.
def sum_two_smallest_numbers(numbers)
  #Your code here
end

Test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13) 
Test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19) 
Test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30) 

題目(Find the stray number)

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3
def stray (numbers)

end

Test.describe("Example test cases") do
  Test.assert_equals(stray([1, 1, 2]), 2)
end

影片解題:
Yes


答案:

# Summing a number's digits
def sumDigits(number)
  number.to_s.chars.map{|x| x.to_i}.sum
end


# Sum of two lowest positive integers
def sum_two_smallest_numbers(numbers)
  numbers.sort[0..1].sum
end


# Find the stray number
def stray (numbers)
  numbers.select{|x| numbers.count(x) == 1}.join.to_i
end

本文同步發布於 小菜的 Blog https://riverye.com/


上一篇
連續刷題看 7 分鐘能刷幾題 Codewars
下一篇
刷題難度逐漸增強
系列文
自我挑戰 Ruby 刷題 30 天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言